package com.qinggeng.project.tool.pay.utils;

import com.alibaba.fastjson.JSONObject;
import com.qinggeng.common.enums.PayTypeEnum;
import com.qinggeng.common.enums.WithdrawalTypeEnum;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.utils.StringUtils;
import com.qinggeng.project.system.domain.Orders;
import com.qinggeng.project.system.domain.UserAccountRecordOrderSingleItem;
import com.qinggeng.project.system.domain.UserBindGsd;
import com.qinggeng.project.system.dto.WithdrawalPayDTO;
import com.qinggeng.project.system.service.IOrdersService;
import com.qinggeng.project.system.service.UserAccountRecordOrderSingleItemService;
import com.qinggeng.project.system.service.UserBindGsdService;
import com.qinggeng.project.tool.pay.domain.AliWithdrawModal;
import com.qinggeng.project.tool.pay.domain.WxWithdrawModal;
import com.qinggeng.project.tool.pay.service.AliPayService;
import com.qinggeng.project.tool.pay.service.WxPayService;
import com.qinggeng.project.tool.third.domain.SysThirdPlatform;
import com.qinggeng.project.tool.third.service.ISysThirdPlatformService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @author 吴鹏飞
 * @date 2020/11/23
 * 提现工具类
 */
@Component
@Slf4j
public class WithDrawalUtils {
    @Resource
    private WxPayService wxPayService;
    @Resource
    private ISysThirdPlatformService sysThirdPlatformService;
    @Resource
    private UserBindGsdService userBindGsdService;
    @Resource
    private AliPayService aliPayService;

    @Value("${wxpay.certPath}")
    private String certUrl;

    @Resource
    private IOrdersService ordersService;

    @Resource
    private UserAccountRecordOrderSingleItemService userAccountRecordOrderSingleItemService;

    /**
     * 提现
     * @param withdrawalPayDTO
     */
    public  void withDrawal(WithdrawalPayDTO withdrawalPayDTO){
        //支付宝提现
        if (WithdrawalTypeEnum.ALI.getValue().equals(withdrawalPayDTO.getType())){
            SysThirdPlatform alipayByGsd = sysThirdPlatformService.selectSysThirdPlatformByCode("alipayByGsd");
            if (alipayByGsd == null){
                log.error("WithDrawalUtils.withDrawal() alipayByGsd is {}",alipayByGsd);
                throw new CustomException("支付宝平台信息为空");
            }
            JSONObject otherParams = JSONObject.parseObject(alipayByGsd.getOtherParams());
            if (otherParams == null){
                log.error("WithDrawalUtils.withDrawal() otherParams is {}",otherParams);
                throw new CustomException("平台参数错误");
            }

            UserBindGsd userBindGsd = userBindGsdService.selectUserBindGsdByUserIdAndPlatform(withdrawalPayDTO.getUserId(), "alipay");
            if (userBindGsd == null){
                log.error("WithDrawalUtils.withDrawal() userBindGsd is {}",userBindGsd);
                throw new CustomException("用户绑定对象为空，userBindGsd=null");
            }
            AliWithdrawModal modal = new AliWithdrawModal();
            modal.setAppid(alipayByGsd.getAppId());
            modal.setPrivateKey(otherParams.getString("privateKey"));
            modal.setPubliceKey(otherParams.getString("publiceKey"));
            modal.setMoney(withdrawalPayDTO.getMoney());
            modal.setAliAccount(userBindGsd.getUniqueId());
            modal.setOrderId(withdrawalPayDTO.getPayNo());
            modal.setRemark("提现");
            modal.setPayerShowName("果舒达");
            modal.setPayeeRealName(userBindGsd.getRealUserName());

            boolean result = aliPayService.withdrawal(modal);
            if (result ){
                return;
            }
        }
        //微信小程序提现
        if (WithdrawalTypeEnum.WX_MINI.getValue().equals(withdrawalPayDTO.getType())){
            SysThirdPlatform wxMini = sysThirdPlatformService.selectSysThirdPlatformByCode("wx_mini");
            if (wxMini == null){
                log.error("WithDrawalUtils.withDrawal() wxMini is {}",wxMini);
                throw new CustomException("微信平台信息为空");
            }
            UserBindGsd userBindGsd = userBindGsdService.selectUserBindGsdByUserIdAndPlatform(withdrawalPayDTO.getUserId(), "wx_mini");
            if (userBindGsd == null){
                log.error("WithDrawalUtils.withDrawal() userBindGsd is {}",userBindGsd);
                throw new CustomException("用户绑定对象为空，userBindGsd=null");
            }
            JSONObject otherParams = JSONObject.parseObject(wxMini.getOtherParams());
            if (otherParams == null){
                log.error("WithDrawalUtils.withDrawal() otherParams is {}",otherParams);
                throw new CustomException("平台参数错误");
            }

            WxWithdrawModal wxWithdrawModal = new WxWithdrawModal();
            wxWithdrawModal.setAppid(wxMini.getAppId());
            wxWithdrawModal.setOpenid(userBindGsd.getUniqueId());
            wxWithdrawModal.setCertUrl(certUrl);
            wxWithdrawModal.setSecurity(otherParams.getString("key"));
            wxWithdrawModal.setMchId(otherParams.getString("mchId"));
            wxWithdrawModal.setMoney(withdrawalPayDTO.getMoney());
            wxWithdrawModal.setTradeNo(withdrawalPayDTO.getPayNo());
            wxWithdrawModal.setDesc("果舒达提现");
            boolean bl =wxPayService.withdrawal(wxWithdrawModal);
            if (bl){
                return;
            }
        }
        //微信提现
        if (WithdrawalTypeEnum.WX.getValue().equals(withdrawalPayDTO.getType())){
            SysThirdPlatform wxApp = sysThirdPlatformService.selectSysThirdPlatformByCode("wx_app");
            if (wxApp == null){
                log.error("WithDrawalUtils.withDrawal() alipayByGsd is {}",wxApp);
                throw new CustomException("微信平台信息为空");
            }
            UserBindGsd userBindGsd = userBindGsdService.selectUserBindGsdByUserIdAndPlatform(withdrawalPayDTO.getUserId(), "wx");
            if (userBindGsd == null){
                log.error("WithDrawalUtils.withDrawal() userBindGsd is {}",userBindGsd);
                throw new CustomException("用户绑定对象为空，userBindGsd=null");
            }
            JSONObject otherParams = JSONObject.parseObject(wxApp.getOtherParams());
            if (otherParams == null){
                log.error("WithDrawalUtils.withDrawal() otherParams is {}",otherParams);
                throw new CustomException("平台参数错误");
            }

            WxWithdrawModal wxWithdrawModal = new WxWithdrawModal();
            wxWithdrawModal.setAppid(wxApp.getAppId());
            wxWithdrawModal.setOpenid(userBindGsd.getUniqueId());
            wxWithdrawModal.setCertUrl(certUrl);
            wxWithdrawModal.setSecurity(otherParams.getString("key"));
            wxWithdrawModal.setMchId(otherParams.getString("mchId"));
            wxWithdrawModal.setMoney(withdrawalPayDTO.getMoney());
            wxWithdrawModal.setTradeNo(withdrawalPayDTO.getPayNo());
            wxWithdrawModal.setDesc("果舒达提现");
            boolean bl =wxPayService.withdrawal(wxWithdrawModal);
            if (bl){
                return;
            }
        }

        throw new CustomException("支付类型错误");

    }

    /**
     * 提现
     * @param
     */
    public  void refund(String orderNo, BigDecimal money) throws Exception {
        Orders orders=ordersService.selectOrdersByOrdersNo(orderNo);
        if (orders ==null ){
            throw new CustomException("订单不存在");
        }
        String payType=orders.getPayType();
        if (StringUtils.isEmpty(payType)){
            throw new CustomException("支付方式为空");
        }
        if (payType.equals(PayTypeEnum.WXPAY.getCode())){
            wxPayService.refund(orderNo,money);
            return;
        }
        if (payType.equals(PayTypeEnum.ALIPAY.getCode())){
            aliPayService.refund(orderNo,money);
            return;
        }
        throw new CustomException("不支持改方式退款");
    }


    /**
     * 单商品退款
     * @param
     */
    public  String refund(String orderNo,Long ordersGoodId, BigDecimal money) throws Exception {
        String result="";
        Orders orders=ordersService.selectOrdersByOrdersNo(orderNo);
        if (orders ==null ){
            throw new CustomException("订单不存在");
        }
        String payType=orders.getPayType();
        if (StringUtils.isEmpty(payType)){
            throw new CustomException("支付方式为空");
        }
        if (payType.equals(PayTypeEnum.WXPAY.getCode())){
            result=  wxPayService.refund(orderNo,ordersGoodId,money);
            UserAccountRecordOrderSingleItem singleItem=new UserAccountRecordOrderSingleItem();
            singleItem.setOrderNo(orderNo);
            singleItem.setOrderGoodsId(ordersGoodId);
            singleItem.setRefundResult(result);
            userAccountRecordOrderSingleItemService.updateRefundResult(singleItem);
            return result;
        }
        if (payType.equals(PayTypeEnum.ALIPAY.getCode())){
            result= aliPayService.refund(orderNo,ordersGoodId,money);
            UserAccountRecordOrderSingleItem singleItem=new UserAccountRecordOrderSingleItem();
            singleItem.setOrderNo(orderNo);
            singleItem.setOrderGoodsId(ordersGoodId);
            singleItem.setRefundResult(result);
            userAccountRecordOrderSingleItemService.updateRefundResult(singleItem);
            return result;
        }
        throw new CustomException("不支持改方式退款");
    }
}
